package com.wd.health.view.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wd.health.R;
import com.wd.health.app.App;
import com.wd.health.event.QpadProgressUtils;
import com.wd.health.model.bean.MoneyBean;
import com.wd.health.model.bean.WXzhifuBean;
import com.wd.health.model.bean.ZfbBean;
import com.wd.health.utils.PayResult;
import com.wd.health.utils.RetrofitManager;
import com.wd.health.utils.WeChatPay;
import com.wd.health.wxapi.WXPayEntryActivity;

import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class RechargeActivity extends AppCompatActivity implements View.OnClickListener {

    private View img_back;
    private RadioButton rb_01;
    private RadioButton rb_02;
    private TextView tv_money;
    private EditText et_money;
    private Button btn_chongzhi;
    private RadioGroup rg_money;

    private static final int SDK_PAY_FLAG = 1;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(RechargeActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    } else if (TextUtils.equals(resultStatus, "8000")){
                        Toast.makeText(RechargeActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();
                    }else {
                        // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                        Toast.makeText(RechargeActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recharge);

        initView();
        initData();
    }

    private void initData() {

    }

    private void initView() {
        img_back = findViewById(R.id.img_back);
        rb_01 = findViewById(R.id.rb_01);
        rb_02 = findViewById(R.id.rb_02);
        tv_money = findViewById(R.id.tv_money);
        et_money = findViewById(R.id.et_money);
        btn_chongzhi = findViewById(R.id.btn_chongzhi);
        rg_money = findViewById(R.id.rg_money);
        btn_chongzhi.setOnClickListener(this);
        img_back.setOnClickListener(this);
        et_money.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                tv_money.setText(s+"00");
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.img_back:
                finish();
                break;
            case R.id.btn_chongzhi:
                if (rb_01.isChecked()){
                    String money = et_money.getText().toString();
                    double s = Double.parseDouble(money);
                    RetrofitManager.getInstance().postWXpay(s, 1, new Observer<WXzhifuBean>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(WXzhifuBean wXzhifuBean) {
                            Log.e("TAG", "支付回调:"+wXzhifuBean);
                            IWXAPI wxapi = WXAPIFactory.createWXAPI(getApplicationContext(), null);
                            wxapi.registerApp("wxe3fcbe8a55cd33ff");
                            PayReq payReq = new PayReq();
                            payReq.appId = wXzhifuBean.getAppId();
                            payReq.nonceStr = wXzhifuBean.getNonceStr();
                            payReq.packageValue = wXzhifuBean.getPackageValue();
                            payReq.partnerId = wXzhifuBean.getPartnerId();
                            payReq.prepayId = wXzhifuBean.getPrepayId();
                            payReq.timeStamp = wXzhifuBean.getTimeStamp();
                            payReq.sign = wXzhifuBean.getSign();
                            wxapi.sendReq(payReq);
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
                }else {
                    String money = et_money.getText().toString();
                    double s = Double.parseDouble(money);
                    RetrofitManager.getInstance().postZfbData(s, 2, new Observer<ZfbBean>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(ZfbBean zfbBean) {
                            String result = zfbBean.getResult();
                            final String orderInfo = result;   // 订单信息
                            Runnable payRunnable = new Runnable() {

                                @Override
                                public void run() {
                                    PayTask alipay = new PayTask(RechargeActivity.this);
                                    Map <String,String> result = alipay.payV2(orderInfo,true);

                                    Message msg = new Message();
                                    msg.what = SDK_PAY_FLAG;
                                    msg.obj = result;
                                    mHandler.sendMessage(msg);
                                }
                            };
                            // 必须异步调用
                            Thread payThread = new Thread(payRunnable);
                            payThread.start();
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
                }

                break;
        }
    }




}